package team.lhc.cms.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import team.lhc.cms.config.QiniuUpload;
import team.lhc.cms.entity.Decoration;
import team.lhc.cms.mapper.DecorationMapper;
import team.lhc.cms.mapper.PicturesMapper;
import team.lhc.cms.service.DecorationService;
import team.lhc.cms.util.RedisUtil;
import team.lhc.cms.util.ResultVO;

import java.util.Map;
import java.util.UUID;

@Service
public class DecorationServiceImpl implements DecorationService {
    @Autowired
    private DecorationMapper decorationMapper;

    @Autowired
    private PicturesMapper picturesMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ResultVO getDecoration(Decoration decoration) {
        String description=decoration.getDescription();
        String propName=decoration.getPropName();
        Integer solve = decoration.getSolve();
        String tel=decoration.getTel();
        return ResultVO.success(decorationMapper.getDecoration(description,propName,solve,tel));
    }

    @Override
    public ResultVO insertDecoration(MultipartFile[] pics, Decoration decoration,String token) {
        try {
            Map<String,Object> hget = (Map<String,Object>)redisUtil.hget(token);
            Integer uid = (Integer) hget.get("uid");
            decoration.setUid(uid);
            decoration.setSolve(0);
            decorationMapper.insertDecoration(decoration);
            for (MultipartFile file:pics){
                String filename = file.getOriginalFilename();
                String suffix  = filename.substring(filename.lastIndexOf(".")+1);
                String newFileName= UUID.randomUUID().toString()+"."+suffix;
                String s = QiniuUpload.updateFile(file, newFileName);
                picturesMapper.insertPic(s,decoration.getDid());
            }
            return ResultVO.success("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultVO.failed("添加失败");
        }
    }

    @Override
    public ResultVO putDecoration(String did) {
        decorationMapper.putDecoration(did);
        return ResultVO.success("修改成功");
    }

    @Override
    public ResultVO delDecoration(String did) {
        decorationMapper.delDecoration(did);
        return ResultVO.success("删除成功");
    }

    @Override
    public Page<Decoration> pageDecoration(int pageNum, int pageSize) {
        Page<Decoration> pages = PageHelper.startPage(pageNum, pageSize);
//        decorationMapper.getDecoration();
        return pages;
    }

}
